package com.zycfc.zsf.boot.mybatis.generator.codegen.db.impl;

import com.zycfc.zsf.boot.mybatis.generator.codegen.db.*;
import com.zycfc.zsf.boot.mybatis.generator.codegen.model.*;
import com.zycfc.zsf.boot.mybatis.generator.codegen.util.*;
import java.sql.*;

public class OracleMapCmd implements MapCmd<ColumnModel>
{
    @Override
    public ColumnModel getObjecFromRs(final ResultSet rs) throws SQLException {
        final ColumnModel model = new ColumnModel();
        final String name = rs.getString("NAME");
        final String humpColName = StringUtil.underLineToHump(name.toLowerCase());
        final String typename = rs.getString("TYPENAME");
        final int length = Integer.parseInt(rs.getString("LENGTH"));
        final int precision = rs.getInt("PRECISION");
        final int scale = rs.getInt("SCALE");
        String description = rs.getString("DESCRIPTION");
        description = ((description == null) ? name : description);
        final String NULLABLE = rs.getString("NULLABLE");
        final String displayDbType = this.getDisplayDbType(typename, length, precision, scale);
        final String javaType = this.getJavaType(typename, precision, scale);
        final boolean isNotNull = "N".equals(NULLABLE);
        model.setColumnName(name);
        model.setHumpColumnName(humpColName);
        model.setColDbType(typename);
        model.setComment(description);
        model.setIsNotNull(isNotNull);
        model.setLength(length);
        model.setPrecision(precision);
        model.setScale(scale);
        model.setDisplayDbType(displayDbType);
        model.setColType(javaType);
        return model;
    }
    
    private String getDisplayDbType(final String dbtype, final long character_length, final int precision, final int scale) {
        if (dbtype.equals("CHAR") || dbtype.equals("VARCHAR2")) {
            return dbtype + "(" + character_length + ")";
        }
        if (dbtype.equals("NVARCHAR2")) {
            return "NVARCHAR2(" + character_length / 2L + ")";
        }
        if (!dbtype.equals("NUMBER")) {
            return dbtype;
        }
        if (scale == 0 && precision > 0) {
            return "NUMBER(" + precision + ")";
        }
        return "NUMBER(" + precision + "," + scale + ")";
    }
    
    private String getJavaType(final String dbtype, final int precision, final int scale) {
        if (dbtype.equals("BLOB")) {
            return "byte[]";
        }
        if (dbtype.indexOf("CHAR") != -1 || dbtype.indexOf("CLOB") != -1) {
            return "String";
        }
        if (dbtype.equals("DATE") || dbtype.indexOf("TIMESTAMP") != -1) {
            return "java.util.Date";
        }
        if (!dbtype.equals("NUMBER")) {
            return "String";
        }
        if (scale > 0) {
            return "Float";
        }
        if (precision < 10) {
            return "Integer";
        }
        return "Long";
    }
}
